﻿/*Date.prototype.getTimeZone=function() {
    var offset = this.getTimezoneOffset(), o = Math.abs(offset);
    return (offset < 0 ? "+" : "-") + ("00" + Math.floor(o / 60)).slice(-2)  + ("00" + (o % 60)).slice(-2);
};*/
var EI = (function (EI) {

    EI.sSysInfo = function() {
        this.CompanyCode="";
        this.CompanyName="";
        this.SvcName = "";
        this.Msg = "";
        this.Flag = 0;
        this.Sender = "";
        this.UserName="";
        this.ForeIP="";
        this.ForeMac="";
        this.ForeMachine="";
        this.UUID = "";
    };

    var type=function(obj){
        var class2type={};
        var toString=class2type.toString;
        var types="Boolean Number String Function Array Date RegExp Object Error";
        types.split(" ").forEach(function(name,i) {
            class2type[ "[object " + name + "]" ] = name.toLowerCase();
        });
        if ( obj == null ) {
            return obj + "";
        }
        return typeof obj === "object" || typeof obj === "function" ?
            class2type[ toString.call(obj) ] || "object" :
            typeof obj;

    }

    var isFunction = function(obj) {
        return type(obj) === "function";
    };

    var isArray = function(obj) {
        return Array.isArray(obj) || type(obj) === "array";
    };

    var isNumeric =function(obj) {
        return !isArray( obj ) && obj - parseFloat( obj ) >= 0;
    };

    EI.PropertyCollection=function() {
        if (typeof EI.PropertyCollection._initialized == "undefined" && this instanceof EI.PropertyCollection) {
            EI.PropertyCollection.prototype.Add = function(key,value){
                this[key] = value;
            };
            EI.PropertyCollection.prototype.Get = function(key){
                return this[key];
            };
            EI.PropertyCollection.prototype.Remove = function(key){
                delete this[key];
            };
            EI.PropertyCollection.prototype.Contains = function(key){
                return this.Get(key) == null?false:true;
            };
            EI.PropertyCollection.prototype.ContainsValue = function(value){
                for(var i=0;i<this.Keys().length;i++){
                    if(this.Get(this.Keys()[i])===value) return true;
                }
                return false;
            };
            EI.PropertyCollection.prototype.Keys = function(){
                return Object.getOwnPropertyNames(this);
            };
            EI.PropertyCollection.prototype.Count = function(){
                return this.Keys().length;
            };
            EI.PropertyCollection.prototype.Clear = function(){
                for(var i=0;i<this.Keys().length;i++){
                    this.Remove(this.Keys()[i]);
                }
            };
            EI.PropertyCollection._initialized = true;
        }

    };

    EI.sDataColumn = function(colName, dataType, colCaption) {
        /*N:Number
         * I:整形；
         * N:浮点型；
         * S:字符型；
         * D:日期型；
         * B:布尔型
         *bool类型的值，xml/json中存储1:true,0:false
         * */
        this.Name = colName;
        this.Caption = colCaption || "C" + colName;
        //this.PrimaryKey = false;
        this.DataType = dataType || "S";
    };

    EI.sDataTable = function () {

        this.Name = undefined;
        this.Columns = new Array();
        this.Rows = new Array();
        this.ExtendedProperties = new EI.PropertyCollection();

        if (typeof EI.sDataTable._initialized == "undefined" && this instanceof EI.sDataTable) {
            EI.sDataTable.prototype.addColumn = function (colName, dataType, colCaption) {
                if (this instanceof EI.sDataTable) {
                    this.Columns.push(new EI.sDataColumn(colName, dataType, colCaption));
                }
            };
            EI.sDataTable.prototype.addColumns = function (colNames) {
                if (this instanceof EI.sDataTable) {
                    for (var arg in arguments) {
                        this.Columns.push(new EI.sDataColumn(arguments[arg]));
                    }
                }
            };
            EI.sDataTable.prototype.addRows = function (rows) {
                if (this instanceof EI.sDataTable) {
                    for (var arg in arguments) {
                        this.Rows.push(arguments[arg]);
                    }
                }
            };
            EI.sDataTable.prototype.addOneRow = function (cells) {
                if (this instanceof EI.sDataTable) {
                    var row = new Array();
                    for (var arg in arguments) {
                        row.push(arguments[arg]);
                    }
                    this.Rows.push(row);
                }
            };
            EI.sDataTable.prototype.setTableName=function(name){
                if(this instanceof EI.sDataTable){
                    this.Name=name;
                }
            };
            EI.sDataTable.prototype.toJsDataTable=function () {
                var jDataTable=new EI.jsDataTable();
                if(this instanceof EI.sDataTable){
                    jDataTable.Name=this.Name;
                    for (var krow in this.Rows) {
                        var colIndex = 0;
                        var xrow = new Object();
                        for (var kcol in this.Columns) {
                            xrow[this.Columns[kcol].Name] = this.Rows[krow][colIndex];
                            colIndex++;
                        }
                        jDataTable.add(xrow);
                    }
                    if(this.ExtendedProperties){
                        jDataTable.ExtendedProperties=this.ExtendedProperties;
                    }
                    return jDataTable;
                }
                return jDataTable;
            };
            EI.sDataTable._initialized = true;
        }

    };

    EI.EIinfo=function() {

        this.SysInfo = new EI.sSysInfo();
        this.Tables = new Array();
        this.ExtendedProperties = new EI.PropertyCollection();

        if (typeof EI.EIinfo._initialized == "undefined" && this instanceof EI.EIinfo) {
            EI.EIinfo.prototype.add = function (dataTable) {
                if (this instanceof EI.EIinfo) {
                    for (var arg in arguments) {
                        if(!arguments[arg].Name)
                            arguments[arg].Name="Table"+(this.getCount()+1);
                        this.Tables.push(arguments[arg]);
                    }
                    if(arguments.length == 0)
                        this.Tables.push(new EI.sDataTable());
                }
            };
            EI.EIinfo.prototype.remove = function () {
                if (this instanceof EI.EIinfo) {
                    for (var arg in arguments) {
                        if(type(arguments[arg])== "string"){
                            if(this.getTableIndex(arguments[arg]) != -1){
                                delete this.Tables[this.getTableIndex(arguments[arg])];
                            }
                        }
                        if(isNumeric(arguments[arg])){
                            if(arguments[arg]!=-1 &&arguments[arg] <this.getCount()-1){
                                delete this.Tables[arguments[arg]];
                            }
                        }
                    }

                }
            };
            EI.EIinfo.prototype.getTable=function (name) {
                if (this instanceof EI.EIinfo) {
                    for (var i in this.Tables){
                        if(this.Tables[i].Name == name){
                            return this.Tables[i];
                        }
                    }
                }
                return null;
            };
            EI.EIinfo.prototype.getTableIndex=function (name) {
                if(this instanceof EI.EIinfo){
                    for (var i in this.Tables){
                        if(this.Tables[i].Name == name){
                            return i;
                        }
                    }
                }
                return -1;

            };
            EI.EIinfo.prototype.contains=function (name) {
                if (this instanceof EI.EIinfo) {
                    if(name){
                        for (var i in this.Tables){
                            if(this.Tables[i].Name == name){
                                return true;
                            }
                        }
                    }
                    return false;
                }
            };
            EI.EIinfo.prototype.merge = function (dataSet) {
                if (this instanceof EI.EIinfo) {
                    for(var arg in arguments){
                        if(isArray(arguments[arg])){
                            for(var i in arguments[arg]){
                                if(this.contains(arguments[arg][i].Name)){
                                    var index=this.getTableIndex(arguments[arg][i].Name);
                                    this.Tables[index]=arguments[arg][i];
                                    //this.getTable(arguments[arg][i].Name);
                                }
                                else {
                                    this.Tables.push(arguments[arg][i]);
                                }
                            }
                        }else {
                            if(this.contains(arguments[arg].Name)){
                                var index=this.getTableIndex(arguments[arg].Name);
                                this.Tables[index]=arguments[arg];
                            }
                            else {
                                this.Tables.push(arguments[arg]);
                            }
                        }

                    }
                }
            };
            EI.EIinfo.prototype.getCount=function () {
                if(this instanceof EI.EIinfo){
                    return this.Tables.length;
                }
            };
            EI.EIinfo.prototype.toJsEIinfo=function () {
                if(this instanceof EI.EIinfo){
                    var jsEIInfo = new EI.jsEIinfo();
                    jsEIInfo.SysInfo = this.SysInfo;
                    for(var i in this.Tables){
                        jsEIInfo.add(this.Tables[i].toJsDataTable());
                    }
                    if(this.ExtendedProperties){
                        jsEIInfo.ExtendedProperties=this.ExtendedProperties;
                    }

                    return jsEIInfo;
                }
                return jsEIInfo;
            };
            EI.EIinfo._initialized = true;
        }

    };

    EI.jsDataTable=function () {

        this.Name= undefined;
        this.Table=new Array();
        this.ExtendedProperties=new EI.PropertyCollection();

        if (typeof EI.jsDataTable._initialized == "undefined" && this instanceof EI.jsDataTable) {
            EI.jsDataTable.prototype.add=function () {
                if (this instanceof EI.jsDataTable){
                    for(var arg in arguments){
                        this.Table.push(arguments[arg]);
                    }
                    if(arguments.length ==0)
                        this.Table.push({});
                }
            };
            EI.jsDataTable.prototype.setTableName=function(name){
                if(this instanceof EI.jsDataTable){
                    this.Name=name;
                }
            };
            EI.jsDataTable.prototype.toDataTable=function () {
                var csTable = new EI.sDataTable();
                if (this instanceof EI.jsDataTable){
                    if(this.Name) csTable.setTableName(name);
                    this.Table.forEach(function (prow, index) {
                        var row=new Array();
                        for (var att in prow) {
                            if (att == "$$hashKey") continue;
                            if(index == 0){ //循环第一行的所有属性，取得列名

                                if (isFunction (prow[att])) {
                                    // 方法
                                } else {
                                    //属性
                                    if(type(prow[att]) === "string"){
                                        csTable.Columns.push({ Name: att ,Type:"S" });
                                    }else if(isNumeric(prow[att])){
                                        csTable.Columns.push({ Name: att ,Type:"S" });
                                    }else if(type(prow[att]) === "boolean"){
                                        csTable.Columns.push({ Name: att ,Type:"B" });
                                    }else if(type(prow[att]) === "date" ){
                                        csTable.Columns.push({ Name: att ,Type:"D" });
                                    }else {
                                        csTable.Columns.push({ Name: att ,Type:"S" });
                                    }
                                }
                            }
                            if (isFunction (prow[att])) {
                                // 方法
                            } else {
                                //属性
                                if(type(prow[att]) === "date"){
                                    var date =new Date(prow[att]);

                                    /*//#微软格式的日期字符串
                                    var myTimezone=date.getTimeZone();
                                    var myTimestamp= +new Date(date);
                                    var dateValue="\/Date("+ myTimestamp+ myTimezone+")\/";
                                    */
                                    var dateValue=date.toISOString();
                                    row.push(dateValue);
                                }else {
                                    row.push(prow[att]);
                                }
                            }
                        }
                        csTable.addRows(row);
                    });
                    csTable.ExtendedProperties=this.ExtendedProperties;
                    return csTable;
                }
            };
            EI.jsDataTable._initialized = true;
        }

    };

    EI.jsEIinfo=function () {

        this.SysInfo = new EI.sSysInfo();
        this.Tables = new Array();
        this.ExtendedProperties = new EI.PropertyCollection();

        if (typeof EI.jsEIinfo._initialized == "undefined" && this instanceof EI.jsEIinfo) {
            EI.jsEIinfo.prototype.add=function (jDataTable) {
                if(this instanceof EI.jsEIinfo){
                    for(var arg in arguments){
                        if(!arguments[arg].Name)
                            arguments[arg].Name="Table"+(this.getCount()+1);
                        this.Tables.push(arguments[arg]);
                    }
                    if(arguments.length ==0)
                        this.Tables.push(new jDataTable());
                }
            };
            EI.jsEIinfo.prototype.remove = function () {
                if (this instanceof EI.jsEIinfo) {
                    for (var arg in arguments) {
                        if(type(arguments[arg])== "string"){
                            if(this.getTableIndex(arguments[arg]) != -1){
                                delete this.Tables[this.getTableIndex(arguments[arg])];
                            }
                        }
                        if(isNumeric(arguments[arg])){
                            if(arguments[arg]!=-1 &&arguments[arg] <this.getCount()-1){
                                delete this.Tables[arguments[arg]];
                            }
                        }
                    }

                }
            };
            EI.jsEIinfo.prototype.getTable=function (name) {
              if(this instanceof EI.jsEIinfo){
                if(name && typeof (name) == "string"){
                    if(this instanceof EI.jsEIinfo){
                        for (var i in this.Tables){
                            if(this.Tables[i].Name == name){
                                return this.Tables[i];
                            }
                        }
                    }
                }
              }
              return null;
            };
            EI.jsEIinfo.prototype.getTableIndex=function (name) {
                if(this instanceof EI.jsEIinfo){
                    for (var i in this.Tables){
                        if(this.Tables[i].Name == name){
                            return i;
                        }
                    }
                }
                return -1;

            };
            EI.jsEIinfo.prototype.contains=function (name) {
                if (this instanceof EI.jsEIinfo) {
                    if(name){
                        for (var i in this.Tables){
                            if(this.Tables[i].Name == name){
                                return true;
                            }
                        }
                    }
                    return false;
                }
            };
            EI.jsEIinfo.prototype.merge = function (dataSet) {
                if (this instanceof EI.jsEIinfo) {
                    for(var arg in arguments){
                        if(isArray(arguments[arg])){
                            for(var i in arguments[arg]){
                                if(this.contains(arguments[arg][i].Name)){
                                    var index=this.getTableIndex(arguments[arg][i].Name);
                                    this.Tables[index]=arguments[arg][i];
                                    //this.getTable(arguments[arg][i].Name);
                                }
                                else {
                                    this.Tables.push(arguments[arg][i]);
                                }
                            }
                        }else {
                            if(this.contains(arguments[arg].Name)){
                                var index=this.getTableIndex(arguments[arg].Name);
                                this.Tables[index]=arguments[arg];
                            }
                            else {
                                this.Tables.push(arguments[arg]);
                            }
                        }

                    }
                }
            };
            EI.jsEIinfo.prototype.firstTable=function () {
               if(this instanceof EI.jsEIinfo){
                   if(this.Tables.length >0){
                       return this.Tables[0];
                   }
               }
            };
            EI.jsEIinfo.prototype.lastTable=function () {
                if(this instanceof EI.jsEIinfo){
                    if(this.Tables.length >0){
                        return this.Tables[this.Tables.length-1];
                    }
                }
            };
            EI.jsEIinfo.prototype.getCount=function () {
                if(this instanceof EI.jsEIinfo){
                    return this.Tables.length;
                }
            };
            EI.jsEIinfo.prototype.toEIinfo=function () {
                if(this instanceof EI.jsEIinfo){
                    var csEIInfo = new EI.EIinfo();
                    csEIInfo.SysInfo = this.SysInfo;
                    for(var i in this.Tables){
                        csEIInfo.add(this.Tables[i].toDataTable());
                    }
                    csEIInfo.ExtendedProperties=this.ExtendedProperties;
                    return csEIInfo;
                }
            };
            EI.jsEIinfo._initialized = true;
        }

    };

    /* ********** ********** **********
     * 将C#风格的Tables转为json风格
     * EIInof2Tables ==> TablesCStoJS
     * *********** ********** **********/

    function ObjectToProperty(obj) {
        if(!(obj instanceof EI.PropertyCollection)){
            if(type(obj)=="object"){
                var properties=new EI.PropertyCollection();
                for(var pro in obj){
                    properties.Add(pro,obj[pro]);
                }
                return properties;
            }
        }
        return obj;
    }
    EI.TableCStoJS = function(csTable) {
        if( !(csTable instanceof EI.sDataTable)){
            var csDataTable=new EI.sDataTable();
            csDataTable.Name=csTable.Name;
            csDataTable.Columns=csTable.Columns;
            csDataTable.Rows=csTable.Rows;
            csDataTable.ExtendedProperties=ObjectToProperty(csTable.ExtendedProperties);
            csTable =csDataTable;
        }
        return csTable.toJsDataTable();
    };

    /* ********** ********** **********
     * 将C#风格的EIInfo转为json风格
     * *********** ********** **********/
    EI.EIInfoCStoJS = function(csEIInfo) {
        if(!(csEIInfo instanceof EI.EIinfo)){
            var info= new EI.EIinfo();
            info.SysInfo = csEIInfo.SysInfo;
            for (var i in csEIInfo.Tables) {
                var csDataTable=new EI.sDataTable();
                csDataTable.Name=csEIInfo.Tables[i].Name;
                csDataTable.Columns=csEIInfo.Tables[i].Columns;
                csDataTable.Rows=csEIInfo.Tables[i].Rows;
                csDataTable.ExtendedProperties=ObjectToProperty(csEIInfo.Tables[i].ExtendedProperties);
                info.add(csDataTable);
            }
            info.ExtendedProperties = ObjectToProperty(csEIInfo.ExtendedProperties);
            //Object.getPrototypeOf(csTables[ktable])  === Object.getPrototypeOf(csTable);
            //Object.getPrototypeOf(csEIInfo)  === Object.getPrototypeOf(info);
            csEIInfo =info;
        }
        return csEIInfo.toJsEIinfo();
    };

    /* ********** ********** **********
     * 将json风格的Tables转为C#风格
     * EIInof2Tables ==> TablesCStoJS
     * *********** ********** **********/
    EI.TableJStoCS=function (jsTable) {
        if( !(jsTable instanceof EI.jsDataTable)){
            var jsDataTable=new EI.jsDataTable();
            jsDataTable.Name=jsTable.Name;
            jsDataTable.Table=jsTable.Table;
            jsDataTable.ExtendedProperties=ObjectToProperty(jsTable.ExtendedProperties);
            jsTable =jsDataTable;
        }
        return jsTable.toDataTable();
    };

    /* ********** ********** **********
    * 将json风格的EIInfo的转为C#风格
    * *********** ********** **********/
    EI.EIInfoJStoCS = function (jEIinfo) {
        if(!(jEIinfo instanceof EI.jsEIinfo)){
            var info= new EI.jsEIinfo();
            info.SysInfo = jEIinfo.SysInfo;
            for (var i in jEIinfo.Tables) {
                var jsDataTable=new EI.jsDataTable();
                jsDataTable.Name=jEIinfo.Tables[i].Name;
                jsDataTable.Table=jEIinfo.Tables[i].Table;
                jsDataTable.ExtendedProperties=ObjectToProperty(jEIinfo.Tables[i].ExtendedProperties);
                info.add(jsDataTable);
            }
            info.ExtendedProperties = jEIinfo.ExtendedProperties;
            //Object.getPrototypeOf(csTables[ktable])  === Object.getPrototypeOf(csTable);
            //Object.getPrototypeOf(csEIInfo)  === Object.getPrototypeOf(info);
            jEIinfo =info;
        }
        return jEIinfo.toEIinfo();
    };

    EI.ObjectToDataTable=function (obj,name) {
        var jsTable1=new EI.jsDataTable();
        jsTable1.add(obj);
        jsTable1.Name=name || "Table1";
        return jsTable1.toDataTable();
    };

    function GetFieldType(fields,key){
        var type='S';
        if(fields[key].type)
        {
            switch(fields[key].type){
                case 'number':
                    type='S';
                    break;
                case 'string':
                    type='S';
                    break;
                case 'date':
                    type='D';
                    break;
            }
        }
        else
            type= "S";
        return type;
    }


    function DSToTable(fields, records,tableName) {

        var csTable=new EI.sDataTable();
        if(tableName)
            csTable.setTableName(tableName);
        records.forEach(function (record,index) {
            var row= new Array();
            for (var prop in fields){
                var columnType= GetFieldType(fields,prop);
                var rowValue=record[prop];
                if(index == 0){
                    csTable.addColumn(prop,columnType);
                }
                if (columnType=="D"){
                    var date =new Date(record[prop]);
                    /*//#微软格式的日期字符串
                     var myTimezone=date.getTimeZone();
                     var myTimestamp= +new Date(date);
                     var dateValue="\/Date("+ myTimestamp+ myTimezone+")\/";*/
                    row.push(date.toISOString());
                }
                else {
                    row.push(rowValue);
                }
            }
            csTable.addRows(row);
        });
        return csTable;
    }

    //获取变更集的CSTale
    //mustMulti 参数：有的后台service全部的增删改表，可以设置为true
    EI.getChangeSet=function (ds) {
        var changeSet=[];
        var fields = ds.options.schema.model.fields;
        if(ds instanceof kendo.data.DataSource){
            if(ds.created()){
                if(ds.created().length > 0){
                    var newChanges = ds.created();
                    var newRecords=DSToTable(fields,newChanges,"INSERT_BLOCK");
                    changeSet.push(newRecords);
                }
            }
            if(ds.updated()){
                if(ds.updated().length>0){
                    var updateChanges = ds.updated();
                    var updatedRecords = DSToTable(fields,updateChanges,"UPDATE_BLOCK");
                    changeSet.push(updatedRecords);
                }
            }
            if(ds.destroyed()){
                if(ds.destroyed().length>0){
                    var destroyChanges = ds.destroyed();
                    var destroyRecords = DSToTable(fields,destroyChanges,"DELETE_BLOCK");
                    changeSet.push(destroyRecords);
                }
            }
        }
        return changeSet;
    };

    return EI;
}(EI || {}));
